#!/usr/bin/env python

import string
import os
import paramiko


##set the last password and the username after changed you want

#setpasswd='hbwangxudong!@#$'
#setuser="wangxudong"
setpasswd=os.sys.argv[2]
setuser=os.sys.argv[1]

#for configure(ip,port,username,password)
#192.168.1.118,6868,root,111111
filepwd="./user.txt"

#read configure from txt
def get_config_file(lines):
    ip="192.168.1.100"
    port=6000
    user="root"
    password="111111"
    temp_str=string.split(lines,',')
    ip=temp_str[0]
    port=int(temp_str[1])
    user=temp_str[2]
    password=temp_str[3]
    password=string.split(password,'\n')
    password = password[0]
    return(ip,port,user,password)


#change the username and the password
def connect_modify(ip_port_user_pwd):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(ip_port_user_pwd[0],ip_port_user_pwd[1],ip_port_user_pwd[2],ip_port_user_pwd[3], timeout=5)
    #    print ip_port_user_pwd[0],ip_port_user_pwd[1],ip_port_user_pwd[2],ip_port_user_pwd[3]
    except:
        print ip_port_user_pwd[0],"network not connect"
        return 0
    stdin, stdout, stderr = client.exec_command("/bin/echo %s|/usr/bin/passwd --stdin %s" %(setpasswd,setuser))
    client.close()
    return 1



def main():
    print setuser,"setpassword",setpasswd
    try:
            f=open(filepwd,"r")
    except:
        print filepwd,"not open ip and passwd file"
        return 0
    for lines in f.readlines() :
        #print lines
         readline=string.split(lines,'\n')
         if len(lines)>20:
            ip_port_user_pwd = get_config_file(lines)
            re=connect_modify(ip_port_user_pwd)
            if re ==1 :
                print ip_port_user_pwd[0],"OK"
        #else
    f.close()

main()
